package com.yimi.appstore.activity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.webkit.WebSettings.RenderPriority;
import android.widget.TextView;
import android.widget.Toast;

import com.yimi.appstore.R;
import com.yimi.appstore.YimiApplication;
import com.yimi.appstore.download2.DownloadManager;
import com.yimi.appstore.download2.FileService;
import com.yimi.appstore.service.WlanService;
import com.yimi.appstore.util.GlobalConsts;
import com.yimi.appstore.util.Util;

public class MainActivity3 extends Activity {

	private static final String TAG = "MainActivity3";

	Context context;
	WebView webView;
	TextView searchTv, resourceTv, downloadTv, moreTv;
	TextView downloadCountTv;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		context = this;
		setContentView(R.layout.activity_main_layout);
		initUi();
		startService(new Intent(context, WlanService.class));
		FileService fileService = new FileService(this);
		YimiApplication.jobList = fileService.getAllDownload(this); // 初始化下载记录
		YimiApplication.downloadHistoryList = fileService.getAllDownloadHistory();
	}
	
	
	@Override
	protected void onResume() {
		super.onResume();
		if(!YimiApplication.jobList.isEmpty()){
			downloadCountTv.setVisibility(View.VISIBLE);
			downloadCountTv.setText(""+YimiApplication.jobList.size());
		}
	}

	private void initUi() {
		downloadCountTv = (TextView) findViewById(R.id.download_count);
		webView = (WebView) findViewById(R.id.webview);
		webView.requestFocus();
		WebSettings settings = webView.getSettings();
		settings.setJavaScriptEnabled(true);
		settings.setRenderPriority(RenderPriority.HIGH);//提高渲染的优先级
		settings.setAppCacheEnabled(true);
		settings.setAppCacheMaxSize(5 * 1024 * 1024);
		
		settings.setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
		settings.setLoadsImagesAutomatically(true);
		
		settings.setUseWideViewPort(true);//网页自适应
		settings.setLoadWithOverviewMode(true);//网页自适应
		settings.setSupportZoom(true);
//		settings.setDefaultZoom(WebSettings.ZoomDensity.FAR);
		
		settings.setAllowFileAccess(true); //设置可以访问文件
		settings.setJavaScriptCanOpenWindowsAutomatically(true);
		settings.setDomStorageEnabled(true);
		settings.setDatabaseEnabled(true);
		settings.setSaveFormData(true);
		settings.setGeolocationEnabled(true); // html得到经纬度
		settings.setDatabasePath("data/data/" + getPackageName() + "/databases");
		webView.setNetworkAvailable(Util.isConnectNetOk(context));
		webView.setHorizontalScrollBarEnabled(false);// 去掉横向的滚动条
		webView.setVerticalScrollBarEnabled(true);
		webView.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
		webView.setWebViewClient(new WebViewClient() {

			@Override
			public boolean shouldOverrideUrlLoading(WebView view, String url) {
				view.loadUrl(url);
				return true;
			}

		});
   
		webView.addJavascriptInterface(this, "yimi");
//		webView.loadUrl("file:///android_asset/index/index.html");
		webView.loadUrl("http://192.168.0.36:8080/yms/pages/index.jsp");
//		 webView.loadUrl("http://a.9game.cn/quality/ablumdetail.html?colmid=2000672&ch=UCdhzqaz&text=azdh_f1");
		findViewById(R.id.search_btn).setOnClickListener(new navigateClickListenr());
		findViewById(R.id.resource_management_btn).setOnClickListener(new navigateClickListenr());
		findViewById(R.id.download_management_btn).setOnClickListener(new navigateClickListenr());
		findViewById(R.id.more_btn).setOnClickListener(new navigateClickListenr());
	}
	

	public void download(String appName, String url) {
		Log.d(TAG, "invoke download() >> url:" + url + ",appName:" + appName);
		DownloadManager.getInstance(context).addDownloadTask(url, appName, "", GlobalConsts.MEDIA_MUSIC);
	}
	
//	public void download(String appName) {
//		Log.d(TAG, "invoke download() >> "+ ",appName:" + appName);
//		DownloadManager.getInstance(context).addDownloadTask(url, appName, "", GlobalConsts.MEDIA_MUSIC);
//	}


	class navigateClickListenr implements OnClickListener {

		@Override
		public void onClick(View v) {
			switch (v.getId()) {
			case R.id.search_btn:
				break;
			case R.id.resource_management_btn:
				Intent i = new Intent(context, ResourceManagementActivity.class);
				startActivity(i);
				break;
			case R.id.download_management_btn:
				Intent intent = new Intent(context, DownloadManagementActivity.class);
				startActivity(intent);
				break;
			case R.id.more_btn:
				
				break;
			}
		}

	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (KeyEvent.KEYCODE_BACK == keyCode && webView.canGoBack()) {
			webView.goBack();
			return true;
		} else if (keyCode == KeyEvent.KEYCODE_BACK) {
			exit();
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}

	private static Boolean isExit = false;
	Handler exitHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			isExit = false;
		}
	};

	/**
	 * 连续点击两次返回退出
	 */
	protected void exit() {
		if (isExit == false) {
			isExit = true;
			Toast.makeText(this, "再按一次返回将退出一米!", Toast.LENGTH_SHORT).show();
			exitHandler.sendEmptyMessageDelayed(0, 2000);
		} else {
			// 暂停所有正在下载的任务
			// 特殊情况，下载还在准备中
			for (int i = 0; i < YimiApplication.jobList.size(); i++) {
				if (YimiApplication.jobList.get(i).getJobStatus() != DownloadManager.STATE_FINISH
						&& YimiApplication.jobList.get(i).getJobStatus() != DownloadManager.STATE_INSTALLED)
					YimiApplication.jobList.get(i).setJobStatus(DownloadManager.STATE_PAUSE);
			}
			for (int i = 0; i < YimiApplication.jobList.size(); i++) {
				if (YimiApplication.jobList.get(i).getJobStatus() != DownloadManager.STATE_FINISH
						&& YimiApplication.jobList.get(i).getJobStatus() != DownloadManager.STATE_INSTALLED)
					Log.d(TAG, "pauseDownloadTask>>" + i);
				DownloadManager.getInstance(context).pauseDownloadTask(i);
			}
			try {
				Thread.sleep(500);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			finish();
			System.exit(0);
		}
	}

}
